/*******************************************************************************
 * Copyright (c) 2012 Till Kolditz.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 * 
 * created on 17.10.2012 at 15:55:23
 * 
 *  Contributors:
 *      Till Kolditz
 *******************************************************************************/
package de.cc.yFilesParser.wizard;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;

import de.kolditz.common.concurrent.Scheduler;
import de.kolditz.common.ui.RunInUIThread;
import de.kolditz.common.ui.dialog.ErrorDialog;
import de.kolditz.common.util.Pair;

/**
 * Subclasses must first call <code>super.run(monitor)</code>! Otherwise this monitor object is null.
 * 
 * @author Till Kolditz - Till.Kolditz@GoogleMail.com
 */
public abstract class GraphMLRunnable implements IRunnableWithProgress
{
    public static class Key
    {
        public String attrFor;
        public String attrId;
        public String attrYFilesType;

        public Key(String attrId, String attrFor, String attrYFilesType)
        {
            this.attrId = attrId;
            this.attrFor = attrFor;
            this.attrYFilesType = attrYFilesType;
        }
    }

    public static class Node
    {
        public String id;
        public String name;
        public String shape;
        public Node parent;
        public List<Node> subNodes;
        public List<Pair<String, String>> attributes;        // this allows multiple attributes with the same key!
        public boolean wasChecked = false; // simplifies search algorithms

        public Node(String id)
        {
            this.id = id;
        }

        public String getId()
        {
            return id;
        }

        public void addSubNode(Node node)
        {
            if (subNodes == null)
                subNodes = new ArrayList<Node>();
            node.parent = this;
            subNodes.add(node);
        }

        public boolean hasSubNodes()
        {
            return subNodes != null && subNodes.size() > 0;
        }

        public void addAttribute(String key, String value)
        {
            if (attributes == null)
                attributes = new ArrayList<Pair<String, String>>();
            attributes.add(new Pair<String, String>(key, value));
        }

        public boolean hasAttributes()
        {
            return attributes != null && attributes.size() > 0;
        }
    }

    protected ConvertWizard wizard;
    protected IProgressMonitor monitor;
    protected XMLStreamReader reader = null;
    protected int unnamedNodeCount = 0;

    public GraphMLRunnable(ConvertWizard wizard)
    {
        this.wizard = wizard;
    }

    @Override
    public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
    {
        this.monitor = monitor;
    }

    /**
     * @param e
     */
    protected void openErrorDialog(final Exception e)
    {
        new RunInUIThread()
        {
            @Override
            protected void inUIThread()
            {
                new ErrorDialog(wizard.getShell(), e).open();
            }
        }.run(null, false);
    }

    /**
     * @throws InvocationTargetException
     */
    protected void createReader(final File sourceFile) throws Exception
    {
        monitor.subTask("Opening source file for reading");

        if (sourceFile == null)
            throw new IllegalArgumentException("parameter sourceFile is null");
        if (!sourceFile.exists())
            throw new IllegalArgumentException("File \"" + sourceFile.getAbsolutePath() + "\" does not exist");
        if (sourceFile.isDirectory())
            throw new IllegalArgumentException('"' + sourceFile.getAbsolutePath() + "\" denotes a directory");

        final XMLInputFactory inFactory = XMLInputFactory.newFactory();

        for (int i = 0; i < 5 && reader == null; ++i)
        {
            ScheduledFuture<XMLStreamReader> future = Scheduler.schedule(new Callable<XMLStreamReader>()
            {
                @Override
                public XMLStreamReader call() throws Exception
                {
                    return inFactory.createXMLStreamReader(new StreamSource(sourceFile));
                }
            }, 0, TimeUnit.MILLISECONDS);

            // wait for loading the file
            while (!future.isDone())
            {
                reader = future.get(100, TimeUnit.MILLISECONDS);
                if (monitor.isCanceled())
                {
                    future.cancel(true);
                    return;
                }
            }
        }

        if (reader == null)
        {
            throw new IllegalStateException(
                    "It seems that the source file could not be opened for reading, but no exception was caught");
        }
    }

    /**
     * resets the wasChecked bit on the given map of nodes
     * 
     * @param nodes
     */
    protected void resetChecked(Map<String, Node> nodes)
    {
        monitor.subTask("resetting node check bits");
        for (Entry<String, Node> entry : nodes.entrySet())
        {
            entry.getValue().wasChecked = false;
            if (monitor.isCanceled())
                return;
        }
    }

    /**
     * @param desiredFor
     *            the value of the "for" attribute - may be null
     * @param desiredYFilesType
     *            the value of the "yfiles.type" attribute - may be null
     * @return a Key object when all non-null arguments match apply
     */
    protected Key parseKey(String desiredFor, String desiredYFilesType)
    {
        monitor.subTask("parsing \"key\"");
        Key key = null;
        boolean isDesiredFor = desiredFor == null;
        boolean isDesiredType = desiredYFilesType == null;
        int count = reader.getAttributeCount();
        String[] names = new String[count];
        String[] values = new String[count];
        String attrId = null, attrFor = null, attrType = null;
        String name, value;
        for (int i = 0; i < count; ++i)
        {
            name = reader.getAttributeLocalName(i);
            names[i] = name;
            value = reader.getAttributeValue(i);
            values[i] = value;
            if ("id".equals(name))
            {
                attrId = value;
            }
            else
                if ("for".equals(name) && (desiredFor == null || desiredFor.equals(value)))
                {
                    isDesiredFor = true;
                    attrFor = value;
                }
                else
                    if ("yfiles.type".equals(name) && (desiredYFilesType == null || desiredYFilesType.equals(value)))
                    {
                        isDesiredType = true;
                        attrType = value;
                    }
        }
        if (isDesiredFor && isDesiredType)
        {
            key = new Key(attrId, attrFor, attrType);
        }
        return key;
    }

    protected Node parseNode(String nodeGraphicsDataKey) throws XMLStreamException
    {
        monitor.subTask("parsing \"node\"");
        Node node = null;

        for (int i = 0; i < reader.getAttributeCount(); ++i)
        {
            if ("id".equals(reader.getAttributeLocalName(i)))
            {
                node = new Node(reader.getAttributeValue(i));
                break;
            }
        }
        if (node == null) // errrrrrr.....
            throw new XMLStreamException("could not find an id for the current node");

        boolean nodeEndNotFound = true;
        String name;
        while (nodeEndNotFound && reader.hasNext())
        {
            switch (reader.next())
            {
                case XMLStreamConstants.START_ELEMENT:
                    name = reader.getLocalName();
                    if ("NodeLabel".equals(name))
                    {
                        boolean doContinue = true;
                        while (doContinue && reader.hasNext())
                        {
                            switch (reader.next())
                            {
                                case XMLStreamConstants.START_ELEMENT:
                                    doContinue = false;
                                    break;
                                case XMLStreamConstants.CHARACTERS:
                                    // takes the very first characters event as the node's name
                                    node.name = reader.getText();
                                    doContinue = false;
                                    break;
                                case XMLStreamConstants.END_ELEMENT:
                                    doContinue = false;
                                    break;
                            }
                        }
                    }
                    else
                        if ("Shape".equals(name))
                        {
                            int count = reader.getAttributeCount();
                            for (int i = 0; i < count; ++i)
                            {
                                if ("type".equals(reader.getAttributeLocalName(i)))
                                {
                                    node.shape = reader.getAttributeValue(i);
                                }
                            }
                        }
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    if ("node".equals(reader.getLocalName()))
                        nodeEndNotFound = false;
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    return node;
            }
        }

        if (node.name == null)
        {
            node.name = "unnamed<" + (unnamedNodeCount++) + ">";
        }

        return node;
    }

    /**
     * Not cancelable
     */
    protected void close()
    {
        monitor.subTask("Closing reader stream");
        ScheduledFuture<?> future = null;
        if (reader != null)
        {
            future = Scheduler.schedule(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        reader.close();
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }, 0, TimeUnit.MILLISECONDS);

            // wait for opening the file
            while (!future.isDone())
            {
                try
                {
                    future.get(100, TimeUnit.MILLISECONDS);
                    if (monitor.isCanceled())
                    {
                        future.cancel(true);
                        return;
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}
